package com.spzx.common.security.aspect;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.security.annotation.PrintLog;
import io.swagger.v3.core.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

@Aspect
@Component
@Slf4j
public class PringLogSpect {
     @Around("@annotation(printLog)")
        public Object around(ProceedingJoinPoint joinPoint, PrintLog printLog){

         if (printLog.isPrintRequestParam()){
             Object[] args = joinPoint.getArgs();
         }
         long start = System.currentTimeMillis();
         MethodSignature signature = (MethodSignature) joinPoint.getSignature();

         ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

         log.info("开始访问日志，时间：{},访问的方法：{},路径：{},参数列表：{}",
                    new Date(),signature.getMethod().getName()
                 ,requestAttributes.getRequest().getRequestURI(),
                 printLog.isPrintRequestParam()? JSON.toJSONString(joinPoint.getArgs()):" ");

         //执行目标方法
         try {
             Object result = joinPoint.proceed();
             log.info("结束访问日志，时间：{},结果：{},耗时:{} ms",new Date(),
                     printLog.isPrintResult()?JSON.toJSONString(result):" ",System.currentTimeMillis()-start);
                return result;
         } catch (Throwable e) {
             throw new RuntimeException(e);
         }



     }
}
